package cn.itedus.lottery.domain.strategy.service.algorithm.impl;

import cn.itedus.lottery.domain.strategy.model.vo.AwardRateInfo;
import cn.itedus.lottery.domain.strategy.service.algorithm.BaseAlgorithm;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: DefaultRateRandomDrawAlgorithm
 * @Description: 必中奖策略抽奖，排掉已经中奖的概率，重新计算中奖范围
 * @Author: szq
 * @Date: 2021-10-11 10:40:20
 */
@Component("entiretyRateRandomDrawAlgorithm")
public class EntiretyRateRandomDrawAlgorithm extends BaseAlgorithm {

    @Override
    public String randomDraw(Long strategyId, List<String> excludeAwardIds) {
        List<AwardRateInfo> awardRateIntervalValList = awardRateInfoMap.getOrDefault(strategyId, new ArrayList<>());
        //排除掉不在抽奖范围的奖品ID集合
        List<AwardRateInfo> differenceAwardRateList = awardRateIntervalValList.stream()
                .filter(t->!excludeAwardIds.contains(t.getAwardId())).collect(Collectors.toList());
        //前置判断
        if (differenceAwardRateList.size() == 0){
            return "";
        }
        if (differenceAwardRateList.size() == 1){
            return differenceAwardRateList.get(0).getAwardId();
        }

        // 获取随机概率值
        int randomVal = this.generateSecureRandomIntCode(100);

        //中奖概率和
        BigDecimal differenceDenominator = differenceAwardRateList.stream().map(AwardRateInfo::getAwardRate).reduce(BigDecimal::add).get();

        //循环获取奖品
        String awardId = "";
        int cursorVal = 0;
        for(AwardRateInfo awardRateInfo : differenceAwardRateList){
            int rateVal = awardRateInfo.getAwardRate().divide(differenceDenominator, 2, BigDecimal.ROUND_UP).multiply(new BigDecimal(100)).intValue();
            if (randomVal <= (cursorVal + rateVal)) {
                awardId = awardRateInfo.getAwardId();
                break;
            }
            cursorVal += rateVal;
        }
        //范围中奖结果
        return awardId;
    }
}
